package eu.jakubiak.md5;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Md5 {

	
	private MessageDigest messageDigest;
	
	public Md5() {
		super();
		try {
			messageDigest = MessageDigest.getInstance("MD5");
		} catch(NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}

	public String calculate(String source) {
		messageDigest.reset();
		try {
			messageDigest.update(source.getBytes("UTF8"));
		} catch(UnsupportedEncodingException e) {
			throw new RuntimeException(e);
		}
        byte digest[] = messageDigest.digest();
        StringBuilder sb = new StringBuilder();
    	for (int i=0;i<digest.length;i++) {
    		String hex = Integer.toHexString(0xFF & digest[i]);
    		if(hex.length()==1) sb.append('0');
    		sb.append(hex);
    	}
    	return sb.toString();
	}
}
